<template>
  <div>
    <div style="padding: 5px 0">
      <el-input v-model="text" @keyup.enter.native="load" style="width: 200px"> <i slot="prefix" class="el-input__icon el-icon-search"></i></el-input>
      <el-button @click="add" type="primary" size="mini" style="margin: 10px">新增</el-button>
      <el-button type="success" @click="exportExcel" size="mini" style="margin: 10px">导出</el-button>
    </div>
    <el-table :data="tableData" border stripe style="width: 100%" id="out-table">
      <el-table-column prop="id" label="ID" width="100" sortable> </el-table-column>
      <el-table-column prop="bookId" label="评论商品ID"></el-table-column>
      <el-table-column prop="userId" label="评论人ID"></el-table-column>
      <el-table-column prop="commentContent" label="评论内容"></el-table-column>
      <el-table-column prop="parentId" label="父ID">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.parentId===0">评论</el-tag>
          <el-tag type="success" v-else>回复--{{scope.row.parentId}}</el-tag>
        </template>
      </el-table-column>
     
      <el-table-column prop="createTime" label="创建时间">
        <template slot-scope="scope">
          {{scope.row.createTime | dataFomart2  }}
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="修改时间">
        <template slot-scope="scope">
          {{scope.row.updateTime | dataFomart2}}
         </template>
      </el-table-column>

      <el-table-column
          fixed="right"
          label="操作"
          width="200">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" circle  @click="edit(scope.row)"></el-button>
          <el-popconfirm
              @confirm="del(scope.row.id)"
              title="确定删除？"
          >
            <el-button type="danger" icon="el-icon-delete" circle slot="reference" style="margin-left: 10px"></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 10px">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-size="pageSize"
        :page-sizes="[2, 5, 10]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <!-- 弹窗   -->
    <el-dialog title="信息" :visible.sync="dialogFormVisible" width="30%" lable-width="100px"
               :close-on-click-modal="false">
      <el-form :model="entity" :rules="addFormRules" ref="addFormRef">
        <el-form-item label="评论商品ID" label-width="150px" prop="bookId">
          <el-input v-model.number="entity.bookId" autocomplete="off" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="评论人ID" label-width="150px" prop="userId">
          <el-input v-model.number="entity.userId" autocomplete="off" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="评论内容" label-width="150px">
          <el-input type="textarea" v-model="entity.commentContent" style="width: 80%"></el-input>
          <!-- <el-input v-model="entity.commentContent" autocomplete="off" style="width: 80%"></el-input> -->
        </el-form-item>
        <el-form-item label="父ID" label-width="150px" prop="parentId">
          <el-input v-model.number="entity.parentId" autocomplete="off" style="width: 80%"></el-input>
        </el-form-item>
      
        

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import API from '../../utils/request'
const url = "/api/msslyyComment/"
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
export default {
  name: "MsslyyComment",
  data() {
    return {
      fileList: [],
      options: [],
      text: '',
      user: {},
      tableData: [],
      pageNum: 1,
      pageSize: 10,
      entity: {},
      total: 0,
      dialogFormVisible: false,
      addFormRules:{
        userId:[
          { required: true, message: '请输入评论人ID', trigger: 'blur' },
          { type: 'number', message: '评论人ID必须为数字值'}
      ],
        bookId:[
        { required: true, message: '请输入评论商品ID', trigger: 'blur' },
        { type: 'number', message: '评论商品ID必须为数字值'}
        ],
        parentId:[
        { type: 'number', message: '父ID必须为数字值'}
       
       
        ],
       
        
      }
    };
  },
  filters:{
    dataFomart(date){
       let dt = new Date(date);//实例化时间对象
       let y = dt.getFullYear();
       let m = dt.getMonth() + 1>10?(dt.getMonth()+ 1):"0"+(dt.getMonth()+ 1);
       let d = dt.getDate()>10?dt.getDate():"0"+dt.getDate(); 
      //笨方法  return y + '-' + m + '-' + d
      //官方方法  注意引号，是tab键上面的符号（ES6的语法）
      return `${y}-${m}-${d}`
    },
    dataFomart2(date){
       let dt = new Date(date);//实例化时间对象
       let y = dt.getFullYear();
       let m = dt.getMonth() + 1>=10?(dt.getMonth()+ 1):"0"+(dt.getMonth()+ 1);
       let d = dt.getDate()>=10?dt.getDate():"0"+dt.getDate(); 
       let hh=dt.getHours()>=10?dt.getHours():"0"+dt.getHours();
       let mm=dt.getMinutes()>=10?dt.getMinutes():"0"+dt.getMinutes();
       let ss=dt.getSeconds()>=10?dt.getSeconds():"0"+dt.getSeconds();
      //笨方法  return y + '-' + m + '-' + d
      //官方方法  注意引号，是tab键上面的符号（ES6的语法）
      return `${y}-${m}-${d}  ${hh}:${mm}:${ss}`
    }
      },
  created() {
    this.user = sessionStorage.getItem("user") ? JSON.parse(sessionStorage.getItem("user")) : {}
    this.$emit('user', this.user);
    this.load()
  },
  methods: {
    exportExcel () {
   var wb = XLSX.utils.table_to_book(document.querySelector('#out-table'))
   var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
   try {
    FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), this.$options.name+'.xlsx')
   } catch (e) { if (typeof console !== 'undefined') console.log(e, wbout) }
   return wbout
  },
    fileSuccessUpload(res) {
      this.entity.file = "http://localhost:9999/files/" + res.data;
      this.fileList = [res.data]
      console.log(res)
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum
      this.load()
    },
    load() {
       API.get(url + "/page", {
          params: {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            name: this.text
          }
       }).then(res => {
          this.tableData = res.data.records || []
          this.total = res.data.total
       })
    },
    add() {
      this.entity = {}
      this.fileList = []
      this.dialogFormVisible = true
    },
    edit(obj) {
      this.entity = JSON.parse(JSON.stringify(obj))
      this.fileList = []
      this.dialogFormVisible = true
    },
    save() {
      this.$refs.addFormRef.validate(async valid => {
          console.log(valid);
          if (!valid) return
          if (!this.entity.id) {
        API.post(url, this.entity).then(res => {
           if (res.code === '0') {
             this.$message({
               type: "success",
               message: "操作成功"
             })
           } else {
             this.$message({
               type: "error",
               message: res.msg
             })
           }
           this.load()
           this.dialogFormVisible = false
        })
      } else {
        API.put(url, this.entity).then(res => {
          if (res.code === '0') {
            this.$message({
              type: "success",
              message: "操作成功"
            })
          } else {
            this.$message({
              type: "error",
              message: res.msg
            })
          }
          this.load()
          this.dialogFormVisible = false
        })
      }
        })
     
    },
    del(id) {
      API.delete(url + id).then(res => {
        this.$message({
          type: "success",
          message: "操作成功"
        })
        this.load()
      })
    }
  },
};
</script>

<style scoped>
</style>
